import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { PageHeaderWrapper } from '@ant-design/pro-layout';

import { Button, Divider, Modal, Tag, message } from 'antd';
import { useRef, useState } from 'react';
import DeviceDetail from './component/DeviceDetail';
import AddDeviceForm from './component/addDevice';
import UpdataDeviceForm from './component/updateDevice';
import styles from './style.less';
import RemoteSelect from '@/components/RemoteSelect';
import { getTenantList } from '@/pages/Tenant/Tenant/service';
import { AddDeviceItem, DeviceItem, UpdateDeviceItem } from './types';
import { addDevice, deleteDevice, pageQueryDevice, updateDevice } from './service';
import { deviceManageBase, deviceServicesStatusMapping } from './utils';
import { pageQuerySimpleRoad } from '../roadManage/service';
import { SUCCESS_CODE } from '@/utils/request';
import { useModel } from 'umi';

export default () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser?.permissions;
  const { 'DEVICE.ADD': add, 'DEVICE.DELETE': Delete, 'DEVICE.UPDATE': update } = currUser;

  const [deviceDetailVisible, setDeviceDetailVisible] = useState<boolean>(false);
  const [addDeviceVisible, setAddDeviceVisible] = useState<boolean>(false);
  const [updateDeviceVisible, setUpdateDeviceVisible] = useState<boolean>(false);
  const [deviceNo, setDeviceNo] = useState<string | null>(null);
  const [deviceData, setDevice] = useState<DeviceItem>({
    id: '',
    device_no: '',
    tenant_id: '',
    type: 0,
    network: 0,
    operator: 0,
  });
  const actionRef = useRef<ActionType>();

  const columns: ProColumns<DeviceItem>[] = [
    {
      title: '所属用户',
      dataIndex: 'tenant_id',
      onFilter: true,
      ellipsis: true,
      render: (_, record) => {
        return record.tenant_name;
      },
      renderFormItem: () => (
        <RemoteSelect
          getPopupContainer={(triggerNode) => triggerNode.parentElement} // 保证选择菜单不会随着页面滚动
          fieldNames={{ key: 'id', value: 'id', label: 'name' }}
          request={() => getTenantList({})}
        />
      ),
    },
    {
      title: '设备编号',
      ellipsis: true,

      dataIndex: 'device_no',
    },
    {
      title: '设备sn号',
      dataIndex: 'sn',
      ellipsis: true,

      search: false,
    },
    {
      title: '设备品牌',
      ellipsis: true,

      dataIndex: 'brand',
    },
    {
      title: '设备类型',
      dataIndex: 'type',
      search: false,
      ellipsis: true,

      render: (_, record) => {
        return <Tag>{deviceManageBase.deviceType[record.type - 1]}</Tag>;
      },
    },
    {
      title: '设备状态',
      dataIndex: 'service_status',
      ellipsis: true,

      valueEnum: () => {
        const map = {};
        deviceServicesStatusMapping.forEach((item) => {
          map[item.key] = {
            text: item.text,
            color: item.color,
            status: item.status,
          };
        });
        return map;
      },
    },
    {
      title: '路段',
      dataIndex: 'road_id',
      ellipsis: true,

      renderFormItem: () => (
        <RemoteSelect
          getPopupContainer={(triggerNode) => triggerNode.parentElement} // 保证选择菜单不会随着页面滚动
          fieldNames={{ key: 'id', value: 'id', label: 'road_name' }}
          request={() => pageQuerySimpleRoad({})}
        />
      ),
    },
    {
      title: '路段名',
      dataIndex: 'road_name',
      ellipsis: true,

      search: false,
    },
    {
      title: 'ip地址',
      dataIndex: 'ip',
      ellipsis: true,

      search: false,
    },
    {
      title: '联网方式',
      dataIndex: 'network',
      ellipsis: true,

      search: false,
      render: (_, record) => {
        return <Tag>{deviceManageBase.netWay[record.network - 1]}</Tag>;
      },
    },
    {
      title: '运营商',
      dataIndex: 'operator',
      ellipsis: true,
      search: false,
      render: (_, record) => {
        return <Tag>{deviceManageBase.operatUser[record.operator - 1]}</Tag>;
      },
    },
    {
      title: '网卡号',
      dataIndex: 'net_number',
      ellipsis: true,
      search: false,
    },
    {
      title: '更新时间',
      dataIndex: 'update_time',
      ellipsis: true,
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      ellipsis: true,
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      ellipsis: true,
      key: 'option',
      render: (
        _text,
        record,
        //  _, action
      ) => {
        const onClickRemove = () => {
          const { device_no } = record;
          Modal.confirm({
            title: `确定要删除 ${device_no} 吗？`,
            content: (
              <>
                <p>删除之后无法撤回，请谨慎操作！</p>
              </>
            ),
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
              await deleteDevice({ device_no });
              actionRef.current?.reload();
            },
            centered: true,
            className: styles.deleteMin,
            style: { height: '15vw' },
          });
        };
        return (
          <>
            {update && (
              <a
                onClick={async () => {
                  setUpdateDeviceVisible(true);
                  setDevice(record);
                }}
              >
                修改
              </a>
            )}
            <Divider type="vertical" />
            <a
              onClick={() => {
                setDeviceNo(record.device_no);
                setDeviceDetailVisible(true);
              }}
            >
              历史数据
            </a>
            {Delete && (
              <>
                <Divider type="vertical" />
                <a onClick={onClickRemove}>删除</a>
              </>
            )}
          </>
        );
      },
    },
  ];

  const addDeviceEvent = async (values: AddDeviceItem) => {
    const res = await addDevice(values);
    if (res.code === SUCCESS_CODE) {
      setAddDeviceVisible(false);
      message.success(res.message);
      actionRef.current?.reload();
    } else {
      message.error(res.message);
    }
  };

  const updateDeviceEvent = async (values: UpdateDeviceItem) => {
    const res = await updateDevice(values);
    if (res.code === SUCCESS_CODE) {
      setUpdateDeviceVisible(false);
      message.success(res.message);
      actionRef.current?.reload();
    } else {
      message.error(res.message);
    }
  };

  return (
    <PageHeaderWrapper>
      <ProTable<DeviceItem>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        editable={{
          type: 'multiple',
        }}
        scroll={{ x: true }}
        request={async (params) => {
          params.page = params.current;
          params.tenant_id = params.tenant_id?.id;
          params.road_id = params.road_id?.id;
          const res = pageQueryDevice(params);
          return res;
        }}
        pagination={{
          defaultPageSize: 10,
          size: 'default',
          showQuickJumper: true,
          showSizeChanger: true,
        }}
        dateFormatter="string"
        headerTitle="设备管理列表"
        toolBarRender={() => [
          <>
            {add && (
              <Button
                key="button"
                icon={<PlusOutlined />}
                type="primary"
                onClick={() => {
                  setAddDeviceVisible(true);
                }}
              >
                添加
              </Button>
            )}
          </>,
        ]}
      />
      {addDeviceVisible && (
        <AddDeviceForm
          onSubmit={addDeviceEvent}
          onCancel={() => setAddDeviceVisible(false)}
          modalVisible={addDeviceVisible}
          visibleHandler={() => setAddDeviceVisible(false)}
        />
      )}
      {updateDeviceVisible && (
        <UpdataDeviceForm
          device={deviceData}
          onSubmit={updateDeviceEvent}
          onCancel={() => setUpdateDeviceVisible(false)}
          modalVisible={updateDeviceVisible}
          visibleHandler={() => setUpdateDeviceVisible(false)}
        />
      )}
      {deviceDetailVisible && deviceNo && (
        <DeviceDetail
          visible={deviceDetailVisible}
          onClose={() => {
            setDeviceDetailVisible(false);
          }}
          deviceNo={deviceNo}
        />
      )}
    </PageHeaderWrapper>
  );
};
